package com.laowang.project.system.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.laowang.common.exception.CustomException;
import com.laowang.common.utils.SecurityUtils;
import com.laowang.common.utils.StringUtils;
import com.laowang.framework.security.LoginUser;
import com.laowang.framework.security.service.TokenService;
import com.laowang.project.system.domain.MyCyhShop;
import com.laowang.project.system.domain.MyCyhShopCattle;
import com.laowang.project.system.domain.MyCyhShopCattleUserRelation;
import com.laowang.project.system.service.MyCyhShopCattleService;
import com.laowang.project.system.service.MyCyhShopCattleUserRelationService;
import com.laowang.project.system.service.MyCyhShopService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.apache.catalina.security.SecurityUtil;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.laowang.framework.aspectj.lang.annotation.Log;
import com.laowang.framework.aspectj.lang.enums.BusinessType;

import org.springframework.web.bind.annotation.*;
import com.laowang.project.system.domain.MyCyhShopCattleUser;
import com.laowang.project.system.service.MyCyhShopCattleUserService;
import com.laowang.framework.web.controller.BaseController;
import com.laowang.framework.web.domain.AjaxResult;
import com.laowang.common.utils.poi.ExcelUtil;
import com.laowang.framework.web.page.TableDataInfo;

import javax.validation.constraints.NotBlank;

/**
 * 商家用户Controller
 * 
 * @author laowang
 * @date 2024-04-26
 */
@Api(tags = "商家用户接口")
@RestController
@RequestMapping("/cattleUser")
public class MyCyhShopCattleUserController extends BaseController {


    @Autowired
    private MyCyhShopCattleUserService myCyhShopCattleUserService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private MyCyhShopCattleUserRelationService myCyhShopCattleUserRelationService;


    @Autowired
    private MyCyhShopCattleService myCyhShopCattleService;

    @Autowired
    private MyCyhShopService myCyhShopService;



    /**
     * 获取商家用户详细信息
     */
    @ApiOperation(value = "商家端  创建商家账号",notes = "")
    @PostMapping(value = "/createAccount")
    public AjaxResult createAccount(@Validated @RequestBody MyCyhShopCattleUser myCyhShopCattleUser) {
        String password1 = myCyhShopCattleUser.getPassword1();
        if (StringUtils.isEmpty(password1)){
            throw new CustomException("再次输入的密码不能为空");
        }
        //Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        myCyhShopCattleUser.setCreated(new Date());
        //myCyhShopCattleUser.setUserId(mid);
        if (!myCyhShopCattleUser.getPassword().equals(password1)){
            throw new CustomException("两次输入的密码不一致");
        }
        List<Integer> ids = myCyhShopCattleUser.getIds();
        if (ids.size() ==0){
            return AjaxResult.error("关联铺不能为空");
        }
        for (Integer id : ids) {
            MyCyhShopCattle myCyhShopCattle = myCyhShopCattleService.selectMyCyhShopCattleById(id);
            if (myCyhShopCattle== null){
                return AjaxResult.error("关联铺信息不存在");
            }
            if (!myCyhShopCattle.getPay().equals(1)){
                return AjaxResult.error(myCyhShopCattle.getName()+ "未支付,请先支付");
            }

        }
        @NotBlank(message = "账号不能为空") String username = myCyhShopCattleUser.getUsername();
        MyCyhShopCattleUser myCyhShopCattleUser1 = myCyhShopCattleUserService.selectByUserName(username);
        if (myCyhShopCattleUser1 !=null){
            return AjaxResult.error("账号已存在");
        }

        myCyhShopCattleUserService.insertMyCyhShopCattleUser(myCyhShopCattleUser);
        for (Integer id : ids) {
            MyCyhShopCattleUserRelation myCyhShopCattleUserRelation = new MyCyhShopCattleUserRelation();
            myCyhShopCattleUserRelation.setShopCattleId(id);
            myCyhShopCattleUserRelation.setShopCattleUser(myCyhShopCattleUser.getId());
            myCyhShopCattleUserRelationService.insertMyCyhShopCattleUserRelation(myCyhShopCattleUserRelation);
        }

        return AjaxResult.success("操作成功");
    }


    @ApiOperation(value = "商家端  商家登录",notes = "")
    @PostMapping(value = "/login")
    public AjaxResult login(@Validated @RequestBody MyCyhShopCattleUser myCyhShopCattleUser) {

        String username = myCyhShopCattleUser.getUsername();
        MyCyhShopCattleUser myCyhShopCattleUser1=  myCyhShopCattleUserService.selectByUserName(username);
        if (myCyhShopCattleUser1 == null){
            throw new CustomException("商家账户不存在");
        }
        if (!myCyhShopCattleUser1.getPassword().equals(myCyhShopCattleUser.getPassword())){
            throw new CustomException("密码有误");
        }
        LoginUser loginUser = new LoginUser();
        loginUser.setUserType("cattle");
        loginUser.setMyCyhShopCattleUser(myCyhShopCattleUser1);
        String token = tokenService.createToken(loginUser);
        //myCyhShopCattleUserService.insertMyCyhShopCattleUser(myCyhShopCattleUser);
        return AjaxResult.success("操作成功",token);
    }

    @ApiOperation(value = "商家端  商家店铺",notes = "")
    @PostMapping(value = "/shops")
    public AjaxResult shops() {
        List<MyCyhShopCattle> list = new ArrayList<>();
        Integer id = SecurityUtils.getLoginUser().getMyCyhShopCattleUser().getId();
        MyCyhShopCattleUserRelation myCyhShopCattleUserRelation = new MyCyhShopCattleUserRelation();
        myCyhShopCattleUserRelation.setShopCattleUser(id);
        List<MyCyhShopCattleUserRelation> myCyhShopCattleUserRelations = myCyhShopCattleUserRelationService.selectMyCyhShopCattleUserRelationList(myCyhShopCattleUserRelation);
        List<Integer> collect = myCyhShopCattleUserRelations.stream().map(MyCyhShopCattleUserRelation::getShopCattleId).collect(Collectors.toList());
        List<MyCyhShopCattle> myCyhShopCattles = myCyhShopCattleService.selectByIds(collect);
        for (MyCyhShopCattle cyhShopCattle : myCyhShopCattles) {
            MyCyhShop myCyhShop = new MyCyhShop();
            myCyhShop.setShopCattleId(cyhShopCattle.getId());
            List<MyCyhShop> myCyhShops = myCyhShopService.selectMyCyhShopListWeb(myCyhShop);
            cyhShopCattle.setMyCyhShopList(myCyhShops);
            list.add(cyhShopCattle);
        }
        return AjaxResult.success("操作成功",list);
    }

    @ApiOperation(value = "商家端   修改商家信息",notes = "")
    @PostMapping("/update")
    public AjaxResult update(@RequestBody MyCyhShopCattleUser myCyhShopCattleUser) {
        if (StringUtils.isNotEmpty(myCyhShopCattleUser.getPassword())  && StringUtils.isNotEmpty(myCyhShopCattleUser.getPassword1())   ){
            if (!myCyhShopCattleUser.getPassword().equals(myCyhShopCattleUser.getPassword1())){
                return AjaxResult.error("密码不一致");
            }
        }

        return toAjax(myCyhShopCattleUserService.updateMyCyhShopCattleUser(myCyhShopCattleUser));
    }

    /**
     * 查询商家用户列表
     */
    @ApiOperation(value = "查询商家用户列表",notes = "")
    @PreAuthorize("@ss.hasPermi('my:cattleUser:list')")
    @GetMapping("/list")
    public TableDataInfo list(MyCyhShopCattleUser myCyhShopCattleUser) {
        startPage();
        List<MyCyhShopCattleUser> list = myCyhShopCattleUserService.selectMyCyhShopCattleUserList(myCyhShopCattleUser);
        return getDataTable(list);
    }
    
    /**
     * 导出商家用户列表
     */
    @ApiOperation(value = "导出商家用户列表",notes = "")
    @PreAuthorize("@ss.hasPermi('my:cattleUser:export')")
    @Log(title = "商家用户", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(MyCyhShopCattleUser myCyhShopCattleUser) {
        List<MyCyhShopCattleUser> list = myCyhShopCattleUserService.selectMyCyhShopCattleUserList(myCyhShopCattleUser);
        ExcelUtil<MyCyhShopCattleUser> util = new ExcelUtil<MyCyhShopCattleUser>(MyCyhShopCattleUser.class);
        return util.exportExcel(list, "cattleUser");
    }

    /**
     * 获取商家用户详细信息
     */
    @ApiOperation(value = "获取商家用户详细信息",notes = "")
    @PreAuthorize("@ss.hasPermi('my:cattleUser:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        return AjaxResult.success(myCyhShopCattleUserService.selectMyCyhShopCattleUserById(id));
    }

    /**
     * 新增商家用户
     */
    @ApiOperation(value = "新增商家用户",notes = "")
    @PreAuthorize("@ss.hasPermi('my:cattleUser:add')")
    @Log(title = "商家用户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MyCyhShopCattleUser myCyhShopCattleUser) {
        return toAjax(myCyhShopCattleUserService.insertMyCyhShopCattleUser(myCyhShopCattleUser));
    }

    /**
     * 修改商家用户
     */
    @ApiOperation(value = "修改商家用户",notes = "")
    @PreAuthorize("@ss.hasPermi('my:cattleUser:edit')")
    @Log(title = "商家用户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MyCyhShopCattleUser myCyhShopCattleUser) {
        return toAjax(myCyhShopCattleUserService.updateMyCyhShopCattleUser(myCyhShopCattleUser));
    }

    /**
     * 删除商家用户
     */
    @ApiOperation(value = "删除商家用户",notes = "")
    @PreAuthorize("@ss.hasPermi('my:cattleUser:remove')")
    @Log(title = "商家用户", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        return toAjax(myCyhShopCattleUserService.deleteMyCyhShopCattleUserByIds(ids));
    }
}
